//
//  WBStatusPictureView.swift
//  新浪微博
//
//  Created by 张甜甜 on 2017/12/2.
//  Copyright © 2017年 sweet. All rights reserved.
//

import UIKit

class WBStatusPictureView: UIView {
    var testHeight:CGFloat = 0
    var viewModel:WBStatusViewModel?{
        didSet{
            testHeight = cacViewSize()
            //设置urls
            urls = viewModel?.picURLs
        }
    }
    //更具视图模型的配图视图的大小，调整显示内容
    private func cacViewSize()->(CGFloat){
        //单图 更具配图视图大小 修改subView[0]的宽高
        //多图 恢复subview【0】的宽高 九宫格布局
        if viewModel?.picURLs?.count == 1 {
            //先获取弟0个图像视图
            let viewSize = viewModel?.pictureViewSize ?? CGSize()
            
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: WBStatusPictureViewOutMargin, width: viewSize.width, height: viewSize.height-WBStatusPictureViewOutMargin)
        }else{
            //多图 无图 九宫格
            let v = subviews[0]
            v.frame = CGRect(x: 0, y: WBStatusPictureViewOutMargin, width: WBStatusPictureItemWidth, height: WBStatusPictureItemWidth)
        }
        return viewModel?.pictureViewSize.height ?? 0
    }
    //配图视图数组
   private var urls:[WBStatusPicture]?{
        didSet{
            //隐藏所有的imageView
            for v in self.subviews {
                v.isHidden = true
            }
            var index = 0
            for url in urls ?? [] {
                //获得对应索引的imageView
                let iv = subviews[index] as! UIImageView
                //4张图像的处理
                if index == 1 && urls?.count == 4{
                    index += 1
                }
                //设置图像
                iv.isHidden = false
                iv .cz_setImage(urlStrin: url.thumbnail_pic, placeHoderImage: nil)
                //判断是否是gif  根据扩展名
                iv.subviews[0] .isHidden = (((url.thumbnail_pic ?? "") as NSString).pathExtension.lowercased() != "gif")
                
                index += 1
            }
        }
    }
    
    override init(frame: CGRect) {
        super .init(frame: frame)
        setUPUi()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("错误信息")
    }
}

extension WBStatusPictureView {
    //cell 中所有的控件都是提前准备好
    //根据数据决定是否显示
    //动态创建会影响性能
    
   private func  setUPUi() {
    self.backgroundColor = superview?.backgroundColor
    //循环创建九个
    self.clipsToBounds = true
    let  count = 3
    let rect = CGRect(x: 0, y: WBStatusPictureViewOutMargin, width: WBStatusPictureItemWidth, height: WBStatusPictureItemWidth)
    
    for i in 0..<count * count {
        let iv = UIImageView()
        //行
        let  row = CGFloat(i / count)
        let col = CGFloat(i % count)
        //列
        let xoffSet = col*(WBStatusPictureItemWidth + WBStatusPictureViewInnerMargin)
        let yOffSet = row*(WBStatusPictureItemWidth + WBStatusPictureViewOutMargin)
        iv.frame = rect.offsetBy(dx:xoffSet , dy: yOffSet)
        iv.clipsToBounds = true
        iv.contentMode = .scaleAspectFill
        self.addSubview(iv)
        //让iv接受用户交互
        iv.isUserInteractionEnabled = true
        //添加手势识别
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapImageView))
        iv.addGestureRecognizer(tap)
        iv.tag = i
        addGifView(iv: iv)
     }
    }
    //像图像视图添加gif指示图像
    private func addGifView(iv:UIImageView){
        let gifImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
        iv.addSubview(gifImageView)
        gifImageView.translatesAutoresizingMaskIntoConstraints = false
        iv.addConstraint(NSLayoutConstraint(item: gifImageView, attribute: .right, relatedBy: .equal, toItem: iv, attribute: .right, multiplier: 1.0, constant: 0))
        iv.addConstraint(NSLayoutConstraint(item: gifImageView, attribute: .bottom, relatedBy: .equal, toItem: iv, attribute: .bottom, multiplier: 1.0, constant: 0))

    }
    
    
    
    
    /// @param selectedIndex    选中照片索引
    /// @param urls             浏览照片 URL 字符串数组
    /// @param parentImageViews
    @objc private func tapImageView(tap:UITapGestureRecognizer){
        guard let iv = tap.view,let pciURLs = viewModel?.picURLs else {
            return
        }
        var selectedIndex = iv.tag
        //针对四张图进行处理
        if pciURLs.count == 4 && selectedIndex > 1 {
            selectedIndex -= 1
        }
        let urls = (pciURLs as NSArray).value(forKey: "thumbnail_pic") as! [String]
        //处理可见图像视图数组
        var imageViewList = [UIImageView]()
        for iv in subviews as! [UIImageView] {
            if !iv.isHidden {
                imageViewList.append(iv)
            }
        }
        //发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBStatusCellBrowserPhotoNotification), object: self, userInfo: [WBStatusCellBrowserPhotoURLsKey:urls ,WBStatusCellBrowserPhotoSelectedIndexKey:selectedIndex,WBStatusCellBrowserPhotoImageViewsKey:imageViewList])
    }
}








